<template>
  <div style="position: relative;">
    <div class="item-box" style="margin-bottom: 12px;">
      <div class="lt flex">
        <slot name="left" />
      </div>
      <div class="rt flex">
        <slot name="right" />
        <div class="handle-box flex" style="margin-left: 40px;">
          <i :class="type=='line'?'iconfont icon-zhexiantu active':'iconfont icon-zhexiantu'" @click="setOptions('line')" />
          <i
            :class="type=='lineArea'?'iconfont icon-jurassic_broken-line active':'iconfont icon-jurassic_broken-line'"
            @click="setOptions('lineArea')"
          />
          <i
            :class="type=='bar'?'iconfont icon-zhuzhuangtu active':'iconfont icon-zhuzhuangtu'"
            style="font-size: 19px;"
            @click="setOptions('bar')"
          />

          <i class="iconfont iconfont icon-xiazai" @click="downloadImg" />
        </div>
      </div>
    </div>
    <div :id="idName" class="chart-table" :style="{height:height,width:'100%'}" />
  </div>
</template>

<script>
import {
  echartsOptions
} from '@/settings.js'
import {
  colorList
} from '@/settings.js'

const grid = {
  top: '40px',
  left: '20px',
  right: '40px',
  bottom: '10px',
  containLabel: true
}

const yAxisItem = {
  type: 'value',
  min: 0,
  axisLine: {
    show: false
  },
  boundaryGap: false,
  axisTick: {
    show: false
  },
  nameTextStyle: {
    color: '#666',
    padding: [0, 10, 5, 0],
    fontSize: 16
  },
  axisLabel: {
    color: '#666',
    fontSize: 16

  }
}
import {
  mapGetters
} from 'vuex'
export default {
  props: {
    unit: {
      default: function() {
        return this.$store.state.user.unit
      },
      type: String
    },
    typeStr: {
      default: '总花费',
      type: String
    },
    daily: {
      default: 126560,
      type: Number
    },
    idName: {
      default: 'chart-table',
      type: String
    },
    height: {
      default: '450px',
      type: String
    },
    xData: { // x轴的数据
      // default: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      type: Object
    },
    seriesData: {
      default: () => {
        return ['1月', '2月']
      }, // y轴的数据
      type: Object
    }

  },

  computed: {
    ...mapGetters([
      'sidebar'
    ]),
    opened() {
      return this.sidebar.opened
    },
    unitTxt() {
      return this.unit === 'USD' ? '$' : '￥'
    },

    // 标题
    diaTitle() {
      let str = ''
      switch (this.typeStr) {
        case 'impressions':
          str = '展示'
          break
        case 'taps':
          str = '点击'
          break
        case 'installs':
          str = '安装'
          break

        case 'avgCptAmount':
          str = 'CPT'
          break
        case 'avgCpaAmount':
          str = 'CPA'
          break
        case 'ttr':
          str = '点击率'
          break
        case 'conversionRate':
          str = '转化率'
          break
      }

      return str
    }

  },
  watch: {
    opened() {
      if (this.cardChart) {
        const that = this
        this.$nextTick(() => {
          setTimeout(() => {
            that.cardChart.resize()
          }, 200)
        })
      }
    },

    xData: {
      deep: true,
      immediate: true,
      handler: function(newV) {
        this.xDatas = newV
        this.setOptions()
      }
    },
    seriesData: {
      deep: true,
      immediate: true,
      handler: function(newV) {
        this.yDatas = newV[0].data
        this.setOptions()
      }

    }
  },
  data() {
    return {
      echartsOptions: echartsOptions,
      cardChart: undefined,
      type: 'line',
      xDatas: '',
      yDatas: '',
      option: {
        grid,
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(250, 250, 250, .8)',
          shaowColor: 'rgba(0, 0, 0, .2)',
          textStyle: {
            color: '#666',
            fontSize: '14px'
          }
        },

        xAxis: {
          type: 'category',
          data: undefined,
          axisTick: {
            // show: false,
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: '#c3c3c3'
            }

          },
          axisLabel: {
            color: '#666',
            margin: 18,
            fontSize: 14
          }

        },
        yAxis: [],
        series: []
      }
    }
  },
  mounted() {
    // 找到盒子
    const idname = this.idName
    this.cardChart = this.$echarts.init(document.getElementById(idname))
    this.setOptions()
  },
  beforeDestroy() {},
  methods: {
    resizeWidth() {
      if (this.cardChart) {
        this.cardChart.resize()
      }
    },

    setOptions(type) {
      if (type) {
        this.type = type
      }

      const that = this

      const xAxis = {
        type: 'category',
        // data: JSON.parse(JSON.stringify(this.xData)),
        data: this.xDatas,
        boundaryGap: this.type === 'bar',
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#E5E5E5;',
            width: 1 // 这里是为了突出显示加上的
          }
        }
      }

      const yAxis = {
        ...yAxisItem,
        min: 0,
        splitNumber: 5,
        name: this.diaTitle
      }

      if (this.diaTitle && this.diaTitle.indexOf('率') > -1) {
        yAxis.axisLabel = {
          formatter: '{value}%'
        }

        yAxis.max = 100
      } else {
        yAxis.axisLabel = {
          formatter: this.unitTxt + '{value}'
        }
        if (this.diaTitle === '点击' || this.diaTitle === '安装' || this.diaTitle === '展示') {
          yAxis.axisLabel = {
            formatter: '{value}'
          }
        }
      }

      var seriesData = {
        type: this.type === 'lineArea' ? 'line' : this.type,
        // data: this.seriesData[0].data || [],
        data: this.yDatas,
        showSymbol: false,
        barMaxWidth: 30,
        boundaryGap: false,
        splitLine: {
          'show': false
        },
        lineStyle: {
          color: 'rgba(84, 138, 249, 1)'
        }, // 线条的样式
        itemStyle: {
          color: 'rgba(84, 138, 249, 1)'
          // opacity: 0 // 为0不会绘制图形拐点消失
        }
      }

      if (this.type === 'line') {
        seriesData = {
          ...seriesData,
          type: 'line',
          symbol: 'circle',
          symbolSize: 12,
          lineStyle: {
            normal: {
              width: 2,
              color: 'rgba(84, 138, 249, 1)'
            }

          }, // 线条的样式
          itemStyle: {
            normal: {
              color: 'rgba(84, 138, 249, 1)',
              borderColor: '#ffffff', // 拐点边框颜色
              borderWidth: 3 // 拐点边框大小
            }
            // opacity: 0 // 为0不会绘制图形拐点消失

          }
        }
      } else if (this.type === 'lineArea') {
        seriesData = {
          ...seriesData,

          type: 'line',
          lineStyle: {
            normal: {
              width: 2,
              color: 'rgba(84, 138, 249, 1)'
            }

          }, // 线条的样式
          itemStyle: {
            normal: {
              color: 'rgba(84, 138, 249, 1)',
              borderColor: '#ffffff', // 拐点边框颜色
              borderWidth: 3 // 拐点边框大小
            }
            // opacity: 0 // 为0不会绘制图形拐点消失

          },
          showSymbol: false,
          areaStyle: {

            emphasis: {
              focus: 'series'
            }
          }

        }
      }

      const options = {
        grid,
        xAxis,
        graphic: {
          type: 'image',
          bottom: 106,
          right: 50,
          style: {
            image: require('@/assets/images/base/logo.png'),
            width: 300
          }
        },
        yAxis: yAxis,
        series: seriesData,
        tooltip: [{
          trigger: 'axis',
          triggerOn: 'mousemove|click',
          backgroundColor: 'rgba(250, 250, 250, .8)',
          shaowColor: 'rgba(0, 0, 0, .2)',
          textStyle: {
            color: '#666',
            fontSize: '14px'
          },
          formatter: function(params) {
            let str = `<p style="font-size: 12px;margin-bottom:12px"> ${params[0].axisValueLabel}</p>`
            params.forEach(item1 => {
              let fix
              let suffix
              var fixArr = ['花费', '总花费', 'CPT', 'CPA', 'CPM']
              var suffixArr = ['点击率', '转化率']
              if (fixArr.indexOf(that.diaTitle) !== -1) {
                fix = that.unitTxt
              }
              if (suffixArr.indexOf(that.diaTitle) !== -1) {
                suffix = '%'
              }
              str +=
                  `
                  <div class="flex" style="width: 120px;font-size: 12px;">
                    <p>
                    <span style="margin-right: 4px;display: inline-block;border-radius: 50%;height: 10px;width: 10px;background-color: ${item1.color};"></span>
                    <span >${that.diaTitle}</span>
                    </p>
                    <p>

                      <span>${fix || ''}${item1.value}${suffix || ''}</span>
                    </p>
                  </div>
              `
            })

            return str
          },

          axiosPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: 'rgba(0, 0, 0, 0.1)'
            }

          }
        }]

      }

      // 设置盒子
      setTimeout(() => {
        this.cardChart.resize()
        this.cardChart.setOption(options, true)
      }, 20)
    },

    // 下载图表
    downloadImg() {
      const picInfo = this.cardChart.getDataURL({
        type: 'png',
        pixelRatio: 1.5, // 放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: '#fff'
      })
      const elink = document.createElement('a')
      elink.download = '3YData图表'

      elink.style.display = 'none'
      elink.href = picInfo
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import '~@/styles/variables.scss';

  .chart-table {
    width: 100% !important;
    overflow: hidden;

  }

  .item-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    padding-right: 0;
    padding-bottom: 4px;
  }

  .handle-box {
    justify-content: flex-end;

    i {
      font-size: 18px;
      color: rgba(172, 182, 194, 1);
      cursor: pointer;
      margin-right: 12px;

      &.active,
      &:hover {
        color: $mainColor1;
      }
    }
  }
</style>
